<template>
    <div class="embroidery-text">

        <div class="embroidery-buttons">
            <button @click="openTextDialog()">文字</button>
        </div>
        <!-- 领标编辑 -->
        <UxDialog :visible="visible" @close="visible = false" class="embroidery-text-dialog">

            <div class="box" v-if="visible">

                <div class="box-preview">
                    <EmbroideryPreview :stitches="pattern.stitches" :colors="pattern.colors" v-if="pattern" />

                    <UxLoading2 v-show="loading" />
                </div>

                <div class="box-options">

                    <div class="row">
                        <div class="row-item">
                            <span>内容</span>
                            <input type="text" v-model="form.text" />
                        </div>
                    </div>

                    <div class="row">
                        <div class="row-item">
                            <span>字体</span>
                            <UxSelect v-model="form.font_family" :options="option_family" />
                        </div>

                        <div class="row-item">
                            <span>变形</span>
                            <UxSelect v-model="form.envelope" :options="option_envelope" />
                        </div>
                    </div>

                    <div class="row">
                        <div class="row-item">
                            <span>高度（磅）</span>
                            <UxInputSlider v-model="form.height" :max="1000" :min="0" :precision="0" :step="1" />
                        </div>

                        <div class="row-item">
                            <span>字宽 %(相对字高)</span>
                            <UxInputSlider v-model="form.width" :max="200" :min="10" :precision="0" :step="1" />
                        </div>
                    </div>

                    <div class="row">
                        <div class="row-item">
                            <span>类型</span>
                            <UxSelect v-model="form.type" :options="option_type" />
                        </div>
                        <!-- <div class="row-item">
                            <span>对齐</span>
                            <UxSelect v-model="form.justification" :options="option_justification" />
                        </div> -->
                    </div>

                    <!-- 弧度 -->
                    <div class="row">
                        <div class="row-item">
                            <span>Arc</span>
                            <UxInputSlider v-model="form.arc" :max="3" :min="-3" :step="0.01" />
                        </div>
                    </div>

                    <div class="row" v-if="form.type === 'ltArc'">
                        <div class="row-item">
                            <span>X1</span>
                            <UxInputSlider v-model="form.X1" :max="2000" :min="-2000" :precision="0" :step="1" />
                        </div>
                        <div class="row-item">
                            <span>Y1</span>
                            <UxInputSlider v-model="form.Y1" :max="2000" :min="-2000" :precision="0" :step="1" />
                        </div>
                    </div>
                    <div class="row" v-if="form.type === 'ltArc'">
                        <div class="row-item">
                            <span>X2</span>
                            <UxInputSlider v-model="form.X2" :max="2000" :min="-2000" :precision="0" :step="1" />
                        </div>
                        <div class="row-item">
                            <span>Y2</span>
                            <UxInputSlider v-model="form.Y2" :max="15000" :min="-15000" :precision="0" :step="1" />
                        </div>
                    </div>
                    <div class="row" v-if="form.type === 'ltArc'">
                        <div class="row-item">
                            <span>X3</span>
                            <UxInputSlider v-model="form.X3" :max="2000" :min="-2000" :precision="0" :step="1" />
                        </div>
                        <div class="row-item">
                            <span>Y3</span>
                            <UxInputSlider v-model="form.Y3" :max="2000" :min="-2000" :precision="0" :step="1" />
                        </div>
                    </div>

                    <!-- 圆形 -->
                    <div class="row" v-if="form.type === 'ltCircle'">
                        <div class="row-item">
                            <span>CenterX</span>
                            <UxInputSlider v-model="form.centerX" :max="1000" :min="0" :precision="0" :step="1" />
                        </div>
                        <div class="row-item">
                            <span>CenterY</span>
                            <UxInputSlider v-model="form.centerY" :max="1000" :min="0" :precision="0" :step="1" />
                        </div>
                    </div>
                    <div class="row" v-if="form.type === 'ltCircle'">
                        <div class="row-item">
                            <span>RefX</span>
                            <UxInputSlider v-model="form.refX" :max="1000" :min="-1000" :precision="0" :step="1" />
                        </div>
                        <div class="row-item">
                            <span>RefY</span>
                            <UxInputSlider v-model="form.refY" :max="1000" :min="-1000" :precision="0" :step="1" />
                        </div>
                    </div>

                    <!-- 彩虹字 -->
                    <div class="rainbow-colors">
                        <div class="row-item">
                            <span>彩虹字</span>
                            <UxSelect v-model="form.isRainbowText" :options="[{ value: 'False', label: 'False' },{ value: 'True', label: 'True' }]" />
                        </div>
                        <div class="embroidery-colors" v-if="form.isRainbowText == 'True'">
                            <el-popover placement="bottom" width="256" trigger="click" v-for="(item,index) in rainbowColors" :key="index">
                                <div class="input-color" slot="reference">
                                    <em :style="{ backgroundColor: item.hex }"></em>
                                    <i class="iconfont icon-xia"></i>
                                </div>
                                <div class="input-picker">
                                    <span v-for="(color,idx) in colors" :key="idx" :style="{ backgroundColor: color.hex }" @click="setColor(index,color)"></span>
                                </div>
                            </el-popover>

                            <button @click="addColor()">+</button>
                        </div>
                    </div>

                    <div style="flex:1"></div>
                    <fieldset>
                        <button @click="onRender()">渲染</button>
                        <button @click="onSure()" type="primary">确定</button>
                    </fieldset>

                </div>

            </div>
        </UxDialog>
    </div>

</template>
<script>
import { readDst, getStitchesByBase64 } from "@/utils/EmbroideryDst.js";
import { Pattern, colors } from "@/utils/EmbroideryPattern.js";


export default {
    data () {
        return {
            visible: false,
            loading: false,
            pattern: null,
            colors: colors,
            rainbowColors: [],
            form: {
                text: 'abcdefg',
                width: 100,
                height: 254,
                centerX: 0,
                centerY: 0,
                refX: 0,
                refY: 0,
                arc: 0,
                X1: 0,
                Y1: 0,
                X2: 0,
                Y2: 0,
                X3: 0,
                Y3: 0,
                font_family: '',
                envelope: '',
                type: 'ltArc',
                justification: '',
                isRainbowText: '',
            },
            option_family: [
                { value: 'Monogram 1', label: 'Monogram 1' },
                { value: '3D Block', label: '3D Block' },
                { value: '3D Shadow Fill', label: '3D Shadow Fill' },
                { value: '3D Shadow Satin', label: '3D Shadow Satin' },
                { value: '2 Col Athl 10-35', label: '2 Col Athl 10-35' },
                { value: 'Full Block 2', label: 'Full Block 2' },
                { value: 'Two Col Athl 2', label: 'Two Col Athl 2' },
                { value: '2 Col Athl 35-75', label: '2 Col Athl 35-75' },
                { value: '2 Col Athl 75-150', label: '2 Col Athl 75-150' },
                { value: 'Bold Block', label: 'Bold Block' },
                { value: 'Allegra Script', label: 'Allegra Script' },
                { value: 'Animals', label: 'Animals' },
                { value: 'Arial Bold 5mm', label: 'Arial Bold 5mm' },
                { value: 'Tail Script', label: 'Tail Script' },
                { value: 'Athletic Outline', label: 'Athletic Outline' },
                { value: 'Avante 5mm', label: 'Avante 5mm' },
                { value: 'Avante', label: 'Avante' },
                { value: 'Block 2 Compact', label: 'Block 2 Compact' },
                { value: 'Athletic Bean', label: 'Athletic Bean' },
                { value: 'Bank 4mm', label: 'Bank 4mm' },
                { value: 'Block 4mm', label: 'Block 4mm' },
                { value: 'Block 2 Comp. Lt', label: 'Block 2 Comp. Lt' },
                { value: 'Block 2', label: 'Block 2' },
                { value: 'Block', label: 'Block' },
                { value: 'Block 2 Light', label: 'Block 2 Light' },
                { value: 'Bolero', label: 'Bolero' },
                { value: 'Brush 6mm', label: 'Brush 6mm' },
                { value: 'Brush 8mm', label: 'Brush 8mm' },
                { value: 'Birdhouse', label: 'Birdhouse' },
                { value: 'Bridge Block', label: 'Bridge Block' },
                { value: 'Brantford', label: 'Brantford' },
                { value: 'Calligraphy', label: 'Calligraphy' },
                { value: 'Canvas Brush', label: 'Canvas Brush' },
                { value: 'Condensed Serif', label: 'Condensed Serif' },
                { value: 'Cin Block', label: 'Cin Block' },
                { value: 'Cin Script', label: 'Cin Script' },
                { value: 'Circle Monogram', label: 'Circle Monogram' },
                { value: 'Cin Italic', label: 'Cin Italic' },
                { value: 'Classic Monogram', label: 'Classic Monogram' },
                { value: 'Compact', label: 'Compact' },
                { value: 'Copperplate', label: 'Copperplate' },
                { value: 'Commercial Scr.', label: 'Commercial Scr.' },
                { value: 'Custom Script', label: 'Custom Script' },
                { value: 'Cyrillic', label: 'Cyrillic' },
                { value: 'Da Vinci', label: 'Da Vinci' },
                { value: 'Designer', label: 'Designer' },
            ],

            option_envelope: [
                { value: 'etRectangle', label: 'etRectangle' },
                { value: 'etBridgeConcaveTop', label: 'etBridgeConcaveTop' },
                { value: 'etBridgeConcaveBottom', label: 'etBridgeConcaveBottom' },
                { value: 'etDoubleConcaveBridges', label: 'etDoubleConcaveBridges' },
                { value: 'etBridgeConvexTop', label: 'etBridgeConvexTop' },
                { value: 'etBridgeConvexBottom', label: 'etBridgeConvexBottom' },
                { value: 'etDoubleConvexBridges', label: 'etDoubleConvexBridges' },
                { value: 'etConcaveTopConvexBottom', label: 'etConcaveTopConvexBottom' },
                { value: 'etConvexTopConcaveBottom', label: 'etConvexTopConcaveBottom' },
                { value: 'etPennantRight', label: 'etPennantRight' },
                { value: 'etPennantLeft', label: 'etPennantLeft' },
            ],
            option_type: [
                { value: 'ltNormal', label: 'ltNormal' },
                { value: 'ltMonogram', label: 'ltMonogram' },
                { value: 'ltArc', label: 'ltArc' },
                { value: 'ltCircle', label: 'ltCircle' },
            ],

            option_justification: [
                { value: 'jtCenter', label: 'jtCenter' },
                { value: 'jtLeft', label: 'jtLeft' },
                { value: 'jtRight', label: 'jtRight' },
                { value: 'jtFillBox', label: 'jtFillBox' },
                { value: 'jtFitToCurve', label: 'jtFitToCurve' },
            ]
        };
    },

    computed: {
        width () {
            return Math.floor(this.form.text.length * this.form.height * this.form.width / 100)
        }
    },
    methods: {

        // 打开文字对话框
        openTextDialog () {
            this.visible = true;
        },

        addColor () {
            const index = Math.floor(Math.random() * this.colors.length);
            this.rainbowColors.push(JSON.parse(JSON.stringify(this.colors[index])));
        },
        setColor (index, event) {
            const colors = this.rainbowColors.slice(0)
            colors[index] = event;
            this.rainbowColors = colors
        },


        getTextPattern (callback) {
            const option = {
                'Type': this.form.type,
                'Text': this.form.text,
                'Font': this.form.font_family,
                'Height': this.form.height,
                'WidthCompression': this.form.width,
                'Envelope': this.form.envelope,
                // 'Recipe': 'Canvas',
                // 'CenterX': this.form.centerX,
                // 'CenterY': this.form.centerY,
                // 'RefX': this.form.refX,
                // 'RefY': this.form.refY,
                // 'X1': this.form.X1,
                // 'Y1': this.form.Y1,
                // 'X2': this.form.X2,
                // 'Y2': this.form.Y2,
                // 'X3': this.form.X3,
                // 'Y3': this.form.Y3,
                'Justification': this.form.justification,
                'IsRainbowText': this.form.isRainbowText,
            }




            if (option.Type == 'ltCircle') {
                option.CenterX = this.form.centerX;
                option.CenterY = this.form.centerY;
                option.RefX = this.form.refX;
                option.RefY = this.form.refY;
                // option.BottomText = option.Text
                // delete option.Text;
            }


            if (option.Type == 'ltArc' || option.Justification == 'jtFitToCurve') {
                if (this.form.arc == 0) {
                    option.Type = 'ltNormal'
                } else {

                    // 半径
                    const r = 0.5 * this.width / Math.PI
                    const k = Math.floor(Math.sin(Math.PI * 45 / 180) * r)
                    const y2 = Math.floor(this.form.arc * r)

                    option.X1 = -k;
                    option.Y1 = this.form.arc > 0 ? -k : k;
                    option.X2 = 0;
                    option.Y2 = y2;
                    option.X3 = k;
                    option.Y3 = this.form.arc > 0 ? -k : k;;


                    this.form.X1 = option.X1;
                    this.form.Y1 = option.Y1;
                    this.form.X2 = option.X2;
                    this.form.Y2 = option.Y2;
                    this.form.X3 = option.X3;
                    this.form.Y3 = option.Y3;
                }
            }



            if (option.IsRainbowText == 'True' && this.rainbowColors.length > 0) {
                option.Text.split('').map((s, i) => {
                    const active = this.rainbowColors[i % this.rainbowColors.length]
                    option[`RainbowColors[${i}].Name`] = active.name;
                    option[`RainbowColors[${i}].Hex`] = active.hex;
                })
            }

            this.loading = true

            this.$http('Drawer.createEmbroideryText', { base64: btoa(JSON.stringify(option)) }).then(res => {

                if (res.code === 0 && res.data.stitches) {

                    const pattern = new Pattern()

                    if (res.data.stitches && res.data.stitches.length > 0) {
                        pattern.stitches = getStitchesByBase64(res.data.stitches)

                        if (option.IsRainbowText == 'True' && this.rainbowColors.length > 0) {
                            const colors = res.data.colors.map((s, i) => this.rainbowColors[i % this.rainbowColors.length])
                            pattern.colors = JSON.parse(JSON.stringify(colors))
                        } else {
                            pattern.colors = res.data.colors
                        }

                        console.log(pattern);
                        this.loading = false
                        callback && callback(pattern)
                    } else {
                        this.loading = false
                        onError('生成失败');
                    }

                    this.loading = false

                } else {
                    this.loading = false;
                    this.$uxMessage.error("Failed to render text.");
                }
            })


            // // RainbowColors

            // console.log(JSON.stringify(option));

            // const base64 = btoa(JSON.stringify(option))
            // const url = 'http://localhost:8000/createEmbroideryText?base64=' + base64
            // // const url = 'drawer/createEmbroideryText?base64=' + base64
            // const onError = (err) => {
            //     console.log(err);
            //     // this.$UxMessage.warning(err);
            // }

            // const xhr = new XMLHttpRequest(); // 新建XMLHttpRequest对象

            // this.loading = true
            // xhr.onreadystatechange = () => {
            //     if (xhr.readyState === 4) { // 成功完成192.168.0.132
            //         // 判断响应结果:
            //         if (xhr.status === 200) {

            //             try {
            //                 const pattern = new Pattern()
            //                 const json = JSON.parse(xhr.responseText || {})

            //                 if (json.data.stitches && json.data.stitches.length > 0) {
            //                     pattern.stitches = getStitchesByBase64(json.data.stitches)

            //                     if (option.IsRainbowText == 'True' && this.rainbowColors.length > 0) {
            //                         const colors = json.data.colors.map((s, i) => this.rainbowColors[i % this.rainbowColors.length])
            //                         pattern.colors = JSON.parse(JSON.stringify(colors))
            //                     } else {
            //                         pattern.colors = json.data.colors
            //                     }

            //                     console.log(pattern);
            //                     this.loading = false
            //                     callback && callback(pattern)
            //                 } else {
            //                     this.loading = false
            //                     onError('生成失败');
            //                 }

            //             } catch (e) {
            //                 console.log(e);
            //                 this.loading = false
            //                 onError(e);
            //             }
            //         } else {
            //             // 失败，根据响应码判断失败原因:
            //             this.loading = false
            //             onError(xhr.status);
            //         }
            //     } else {
            //         // HTTP请求还在继续...
            //     }
            // }

            // // 发送请求:
            // xhr.open('get', url, true);
            // xhr.send();
        },

        onRender () {
            this.getTextPattern((pattern) => {
                this.pattern = pattern
            })
        },

        // 确定
        onSure () {
            this.getTextPattern((pattern) => {
                this.visible = false;
                this.$emit('upload', pattern)
            })
        }
    },
    mounted () {

        // this.demo()

    }
};
</script>
<style lang="scss" scoped>
.embroidery-text {
    display: flex;
    flex-direction: column;
}

.embroidery-buttons {
    ul {
        display: flex;
        flex-wrap: wrap;
    }
    li {
        width: 40px;
        height: 40px;
        display: flex;
        padding: 5px;
        span {
            width: 100%;
            height: 100%;
        }
    }
}

.box {
    padding: 20px;
    width: 800px;
    display: flex;
    align-items: center;

    .box-preview {
        flex: 1;
        background-color: #fafafa;
        border: 1px solid #ddd;
        position: relative;
        border-radius: 5px;
        &::before {
            content: '';
            display: block;
            padding-bottom: 100%;
        }

        .embroidery-preview {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
        }
    }

    .box-options {
        width: 300px;
        margin-left: 20px;
        display: flex;
        flex-direction: column;

        .row {
            display: flex;
            margin-top: 16px;
        }
        .row-item {
            flex: 1;
            & + .row-item {
                margin-left: 10px;
            }
            & > span {
            }

            .form-select::v-deep blockquote {
                overflow: auto;
                height: 500px;
            }
        }

        input {
            height: 30px;
        }

        .embroidery-colors {
            display: flex;
            flex-wrap: wrap;
            min-height: 100px;
            margin: 0 -5px 10px;

            button {
                width: 30px;
                height: 30px;
                padding: 0;
                margin: 5px;
            }
            &::v-deep > span {
                margin: 5px;
            }
            .input-color {
                width: 30px;
                height: 30px;
                display: flex;
                position: relative;
                em {
                    width: 100%;
                    height: 100%;
                    border-radius: 4px;
                    border: 1px solid #ddd;
                }
                i {
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    transform: translate(-50%, -50%);
                    color: #fff;
                    text-shadow: 0 0 3px rgba($color: #000000, $alpha: 0.5);
                }
            }
        }

        .input-slider {
            height: 30px;

            &::v-deep .slider-warp {
                margin-right: 0;
            }
            &::v-deep input {
                position: absolute;
                right: 0;
                top: -20px;
                height: 24px;
            }
        }

        .form-select {
            height: 30px;
            width: auto;
            &:v-deep ul {
                max-height: 300px;
                overflow: auto;
            }
        }

        fieldset {
            display: flex;
            margin-top: 10px;
            button {
                flex: 1;
            }
        }
    }
}

.embroidery-text-dialog {
    &::v-deep .dialog-content {
        overflow: visible;
    }
    &::v-deep .dialog-body {
        overflow: visible;
    }
}

.input-picker {
    display: flex;
    flex-wrap: wrap;
    span {
        margin: 5px;
        width: 30px;
        height: 30px;
        position: relative;
        border-radius: 4px;
        overflow: hidden;
        border: 1px solid #ddd;
        cursor: pointer;
    }
}
</style>
